package com.fkdx.datasource;


import com.zaxxer.hikari.HikariDataSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * 数据源和事务配置
 */
@Configuration
@Slf4j
public class DataSourceConfig {

    @Resource
    private DBProperties dbProperties;

    @Bean
    public DataSource dataSource() {
        HikariDataSource masterDataSource = addProperties(dbProperties.getMaster());

        // 按照目标数据源名称和目标数据源对象的映射存放在map中
        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put("master", masterDataSource);

        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        dynamicDataSource.setTargetDataSources(targetDataSources);
        dynamicDataSource.setDefaultTargetDataSource(masterDataSource);
        return dynamicDataSource;
    }

    @Bean
    public PlatformTransactionManager txManager() {
        return new DataSourceTransactionManager(dataSource());
    }

    private HikariDataSource addProperties(HikariDataSource source) {
        // 是否自定义配置，为true时下面两个参数才生效
        source.addDataSourceProperty("cachePrepStmts", "true");
        // 连接池大小默认25，官方推荐250-500
        source.addDataSourceProperty("prepStmtCacheSize", "250");
        // 单条语句最大长度默认256，官方推荐2048
        source.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
        // 新版本MySQL支持服务器端准备，开启能够得到显著性能提升
        source.addDataSourceProperty("useServerPrepStmts", "true");
        //source.addDataSourceProperty("useLocalSessionState", "true");
        //source.addDataSourceProperty("useLocalTransactionState", "true");
        source.addDataSourceProperty("rewriteBatchedStatements", "true");
        source.addDataSourceProperty("cacheResultSetMetadata", "true");
        source.addDataSourceProperty("cacheServerConfiguration", "true");
        source.addDataSourceProperty("elideSetAutoCommits", "true");
        source.addDataSourceProperty("maintainTimeStats", "false");
        return source;
    }
}
